package cn.nfwx.tv.controller.player;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGAImageView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.ChannelAdapter2;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.controller.AdvertiseController;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.controller.TVHotViewController;
import cn.nfwx.tv.controller.TVProgramsViewController;
import cn.nfwx.tv.fragment.dialog.QuitAppDialogFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ActivityHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.RecyclerViewHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.util.AnimationUtil;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.NetworkUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.TSnackbarUtil;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.AudioVisualView;
import cn.nfwx.tv.widget.AutoAdjustRecylerView;
import cn.nfwx.tv.widget.LoadView;
import cn.nfwx.tv.widget.QpopReviewView;
import cn.nfwx.tv.widget.TitleBar;
import cn.nfwx.tv.widget.TouchUltraViewPager;
import cn.nfwx.tv.widget.nfwxplayer.INfwxVideoPlayer;
import cn.nfwx.tv.widget.nfwxplayer.NfwxButtonView;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayerController;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayerManager;

import static cn.nfwx.tv.activity.AdvertiseActivity.TYPE_JIAOBIAO;

public abstract class BasePlayerController extends NfwxVideoPlayerController implements View.OnClickListener, Handler.Callback, BaseQuickAdapter.OnItemClickListener {

    protected ImageView iv_player_thumb;
    protected TextView title_channel_name, tv_vodplayer_back;

    // 中间模块
    protected RelativeLayout gesture_volume_layout, gesture_bright_layout, gesture_progress_layout;
    protected ImageView gesture_iv_player_volume, gesture_iv_player_bright, gesture_iv_player_progress;
    protected TextView geture_tv_volume_percentage, geture_tv_bright_percentage, geture_tv_progress_percentage;

    protected TitleBar player_bar;
    protected RelativeLayout rl_player_left, ll_audio;
    protected LinearLayout player_bottom, ll_home_top, player_right, ll_bottom, ll_titlebar;
    protected RecyclerView channel_recyclerView;
    protected RecyclerViewHelper recyclerViewHelper;
    protected ImageView vodplayer_back_btn, iv_audio_play, iv_audio_reflected, iv_audio_img;
    protected TextView company_btn;
    protected QpopReviewView qrv_review;
    protected NfwxButtonView pcv_home;
    protected LoadView loadview;
    protected TimelineController tvc_controller;
    protected AudioVisualView vv_audio_1, vv_audio_2;
    protected View iv_qpop_quit, tv_qpop_quit;
    protected FrameLayout view_player;
    protected SVGAImageView svga_iv;
    protected TouchUltraViewPager vp_player;

    protected ChannelAdapter2 channelAdapter;

    private static final int ACTION_LAUNCHER = 1; // 广告图
    private static final int ACTION_SHOW = 2; //
    private static final int ACTION_HIDDEN = 3; // 5秒钟后隐藏控件
    private static final int ACTION_QUIT = 4; // 退出应用提示
    private static final int ACTION_LOAD = 5; // 5分钟刷新一次数据
    private static final int ACTION_TITLE = 6; // titlebar刷新
    private static final int ACTION_JIAOBIAO = 7; // 角标显示
    private static final int ACTION_JIAOBIAO_HIDDEN = 8; // 角标消失 针对png

    private static final int HIDDENTIME = 15000;
    private static final int JIAOBIAOTIME = 8000;
    protected static final int durationMillis = 200;
    private static final int TITLE_TIME_UPDATE = 30000;

    protected boolean _isShow = true; // 是否显示所有控件
    protected boolean _isLock = false; // 是否再锁屏
    protected boolean _isQuit = false; // 是否退出应用
    protected boolean _isClip = false;
    protected boolean _isReview = false;
    protected boolean _isnetworkError;
    protected boolean _isHandPause = false;

    protected Handler mHandler;
    protected Handler backgroundHandler;
    protected final String REFRESH_BACKGROUND_HANDLER = "REFRESH_BACKGROUND_HANDLER";

    public BasePlayerController(@NonNull Context context) {
        this(context, null);
    }

    public BasePlayerController(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BasePlayerController(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 打开回看列表
     */
    protected void openProgram() {
        pcv_home.hiddenBubble();
        refreshView(false);
    }

    /**
     * 播放结束
     */
    protected void playComplete() {
        loadview.playComplete(view_player, hasNextProgram(), getFromState());
    }

    /**
     *
     */
    protected void playAdvertComplete(){

    }

    /**
     * 是否有下一个节目
     *
     * @return
     */
    protected boolean hasNextProgram() {
        return false;
    }

    /**
     * 点播来源
     *
     * @return
     */
    protected int getFromState() {
        return 0;
    }

    /**
     * 播放下一个
     */
    protected void nextProgram() {

    }

    /**
     * 返回直播
     */
    protected abstract void backLive();

    protected abstract boolean isDownedPlay();

    /**
     * 下载视频
     */
    protected void download() {

    }

    /**
     * 分享视频
     */
    protected void share() {

    }

    /**
     * 获取直播信息
     */
    protected String getGid() {
        return "all";
    }

    /**
     * 打开企业图标
     */
    protected void openCompany() {
        //pcv_home.hiddenBubble();
    }

    /**
     * 搜索
     */
    protected void openSearch() {
        pcv_home.hiddenBubble();
    }

    /**
     * 热门节目
     */
    protected void openHotLives() {
        pcv_home.hiddenBubble();
        refreshView(false);
    }

    /**
     * 我的页面
     */
    protected void openMine() {
        pcv_home.hiddenBubble();
    }

    /**
     * 剪切页面
     */
    protected void openclip() {
        vp_player.setDisable(true);
        pcv_home.hiddenBubble();
        svga_iv.stopAnimation(true);
        svga_iv.setImageDrawable(null);
        mHandler.removeMessages(ACTION_JIAOBIAO);
        mHandler.removeMessages(ACTION_JIAOBIAO_HIDDEN);
    }

    /**
     * 取消剪切
     */
    protected void cancelclip() {
        vp_player.setDisable(false);
        mHandler.removeMessages(ACTION_JIAOBIAO);
        mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO, AdvertiseController.getInstance().getInterval(mContext, TYPE_JIAOBIAO, getGid()));
    }

    /**
     * 确实剪切
     */
    protected void sureclip() {

    }

    /**
     * 4g播放
     */
    protected void sure4gplay() {
    }

    /**
     * 回看
     */
    protected void openReview() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.layout_controller;
    }

    @Override
    protected void initView() {
        mHandler = new Handler(this);

        iv_player_thumb = findView(R.id.iv_player_thumb);
        title_channel_name = findView(R.id.title_channel_name);
        tv_vodplayer_back = findView(R.id.tv_vodplayer_back);

        qrv_review = findView(R.id.qrv_review);
        pcv_home = findView(R.id.pcv_home);
        pcv_home.attachController(this);
        player_bar = findView(R.id.player_bar);
        rl_player_left = findView(R.id.rl_player_left);
        ll_audio = findView(R.id.ll_audio);
        player_bottom = findView(R.id.player_bottom_lin);
        ll_home_top = findView(R.id.ll_home_top);

        player_right = findView(R.id.player_right_lin);
        channel_recyclerView = findView(R.id.tv_channel_recyclerView);
        channel_recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));//设置横向滚动
        recyclerViewHelper = new RecyclerViewHelper().attachToRecyclerView(channel_recyclerView);

        tvc_controller = findView(R.id.tvc_controller);

        tvc_controller.setPlayerView((ImageView) findView(R.id.player_start_btn));
        tvc_controller.setBmpView((ImageView) findView(R.id.iv_player_thumb));

        iv_qpop_quit = findView(R.id.iv_qpop_quit);
        tv_qpop_quit = findView(R.id.tv_qpop_quit);

        vodplayer_back_btn = findView(R.id.vodplayer_back_btn);
        tv_vodplayer_back = findView(R.id.tv_vodplayer_back);
        ll_bottom = findView(R.id.ll_bottom);
        ll_titlebar = findView(R.id.ll_titlebar);

        // 羊城交通台
        ll_audio = findView(R.id.ll_audio);
        vv_audio_1 = findView(R.id.vv_audio_1);
        vv_audio_2 = findView(R.id.vv_audio_2);
        iv_audio_play = findView(R.id.iv_audio_play);
        iv_audio_reflected = findView(R.id.iv_audio_reflected);
        iv_audio_img = findView(R.id.iv_audio_img);

        // svga
        svga_iv = findView(R.id.svga_iv);

        channelAdapter = new ChannelAdapter2();
        channel_recyclerView.setAdapter(channelAdapter);
        ((SimpleItemAnimator) channel_recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        channelAdapter.initData();

        vp_player = findView(R.id.vp_player);

        company_btn = findView(R.id.company_btn);

        //vp_player.setVisibility(GONE);

        initGesture();
        initLoadView();
        initViewPager();
        initListener();
    }

    @Override
    protected void init() {
        mHandler.removeMessages(ACTION_TITLE);
        mHandler.sendEmptyMessage(ACTION_TITLE);
    }

    @Override
    public void release() {
        cancelUpdateProgressTimer();
        tvc_controller.release();
        svga_iv.stopAnimation(true);
        svga_iv.setCallback(null);
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initGesture() {
        gesture_volume_layout = findView(R.id.gesture_volume_layout);
        gesture_bright_layout = findView(R.id.gesture_bright_layout);
        gesture_progress_layout = findView(R.id.gesture_progress_layout);
        gesture_iv_player_volume = findView(R.id.gesture_iv_player_volume);
        gesture_iv_player_bright = findView(R.id.gesture_iv_player_bright);
        gesture_iv_player_progress = findView(R.id.gesture_iv_player_progress);
        geture_tv_volume_percentage = findView(R.id.geture_tv_volume_percentage);
        geture_tv_bright_percentage = findView(R.id.geture_tv_bright_percentage);
        geture_tv_progress_percentage = findView(R.id.geture_tv_progress_percentage);
    }

    private void initLoadView() {
        view_player = findView(R.id.view_player);
        if (loadview != null) {
            loadview = null;
        }
        loadview = new LoadView(mContext);
        loadview.setTextColor(Color.WHITE);
        loadview.setOnLoadClickLisener(new LoadView.OnLoadClickListener() {
            @Override
            public void onreload() {
                if (loadview.getStats() == LoadView.NET4G) {
                    SharePrefUtil.save4gstautus(mContext, true);
                    sure4gplay();
                    //WifiHelper.stopScan();
                } else if (loadview.getStats() == LoadView.LOADERROR) {
                    AccountHelper.getInstance().requestIp(mContext, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(final String value) {
                            ThreadHelper.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (TextUtils.isEmpty(value)) {
                                        loadview.loadError(view_player);
                                    } else {
                                        if (NetworkHelper.getInstance().hasConnection(mContext)) {
                                            reStart();
                                        } else {
                                            loadview.netError(view_player);
                                        }
                                    }
                                }
                            });
                        }
                    });
                } else if (loadview.getStats() == LoadView.PLAYCOMPLETE) {
                    openProgram();
                } else {
                    if (NetworkHelper.getInstance().hasConnection(mContext)) {
                        reStart();
                    } else {
                        loadview.netError(view_player);
                    }
                }
            }

            @Override
            public void onnext() {
                if (loadview.getStats() == LoadView.PLAYCOMPLETE) {
                    nextProgram();
                }
            }
        });
        loadview.startLoading(view_player);
    }

    Map<Integer, View> mViews = new HashMap<>();
    int vpPosition = 100;

    private void initViewPager() {
        //vp_player.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        vp_player.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.layout_loading_view, null);
                view.setTag(position);
                mViews.put(position, view);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
                mViews.remove(position);
            }
        });

        vpPosition = 100;
        vp_player.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //LogUtil.v("ttt", position + "---(" + positionOffset + "----(" + positionOffsetPixels);
                if (positionOffset == 0 && positionOffsetPixels == 0) {
                    for (Integer p : mViews.keySet()) {
                        if (mViews.get(p) != null) {
                            mViews.get(p).setVisibility(View.VISIBLE);
                        }
                    }
                    if (mViews.get(position) != null) {
                        mViews.get(position).setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void onPageSelected(int position) {
                //LogUtil.v("ttt", position + "--onPageSelected-");
                if (mViews != null) {
                    for (Integer p : mViews.keySet()) {
                        if (mViews.get(p) != null) {
                            mViews.get(p).setVisibility(View.VISIBLE);
                        }
                    }
                    if (mViews.get(position) != null) {
                        mViews.get(position).setVisibility(View.INVISIBLE);
                    }
                }
                if (vpPosition > position) {
                    vpPosition = position;
                    playBack();
                } else if (vpPosition < position) {
                    vpPosition = position;
                    playNext();
                }
            }
        });
        vp_player.setTouchListener(new TouchUltraViewPager.OnTouchListener() {
            @Override
            public void touchEvent(MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    onTouchEvent(event);
                }
            }
        });
        vp_player.setCurrentItem(vpPosition);
    }

    private void initListener() {
        tv_vodplayer_back.setOnClickListener(this); // 返回直播
        vodplayer_back_btn.setOnClickListener(this); // 返回直播
        pcv_home.setClickListener(this); // 回看
        findView(R.id.review_btn).setOnClickListener(this); // 回看
        findView(R.id.lock_btn).setOnClickListener(this); // 锁
        findView(R.id.unlock_btn).setOnClickListener(this); // 解锁
        findView(R.id.clip_btn).setOnClickListener(this);
        findView(R.id.fire_btn).setOnClickListener(this); // 热门
        findView(R.id.search_btn).setOnClickListener(this); //搜索
        findView(R.id.mine_btn).setOnClickListener(this); // 我的
        findView(R.id.download_btn).setOnClickListener(this); // 下载
        findView(R.id.share_btn).setOnClickListener(this);
        company_btn.setOnClickListener(this); // 企业视频
        svga_iv.setOnClickListener(this); // svga
        tvc_controller.setProgramItemListener(this);
        iv_qpop_quit.setOnClickListener(this);
        //findView(R.id.network_free_wifi).setOnClickListener(this);
        //findView(R.id.network_sure).setOnClickListener(this);
        iv_audio_play.setOnClickListener(this);
        channelAdapter.setOnItemClickListener(this);

        svga_iv.setCallback(new SVGACallback() {
            @Override
            public void onPause() {

            }

            @Override
            public void onFinished() {
                svga_iv.stopAnimation(true);
                svga_iv.setClickable(false);
                if (mHandler != null) {
                    mHandler.removeMessages(ACTION_JIAOBIAO);
                    mHandler.removeMessages(ACTION_JIAOBIAO_HIDDEN);
                    mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO, AdvertiseController.getInstance().getInterval(mContext, TYPE_JIAOBIAO, getGid()));
                }
                svga_iv.setCallback(null);
                svga_iv.setCallback(this);
            }

            @Override
            public void onRepeat() {

            }

            @Override
            public void onStep(int i, double v) {

            }
        });
        svga_iv.setClickable(false);
        int stats = AdvertiseController.getInstance().loadJiaoBiao(mContext, svga_iv, getGid());
        if (stats == AdvertiseController.IMG_TYPE_SVGA) {
            mHandler.removeMessages(ACTION_JIAOBIAO_HIDDEN);
        } else if (stats == AdvertiseController.IMG_TYPE_PNG) {
            mHandler.removeMessages(ACTION_JIAOBIAO);
            mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO_HIDDEN, AdvertiseController.getInstance().getDurTime(mContext, TYPE_JIAOBIAO));
        } else if (stats == AdvertiseController.IMG_TYPE_NO) {
            mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO, JIAOBIAOTIME);
        }
    }


    @Override
    public void setVideoPlayer(INfwxVideoPlayer videoPlayer) {
        super.setVideoPlayer(videoPlayer);
        pcv_home.attach(videoPlayer);
        tvc_controller.attach(videoPlayer);
    }

    @Override
    public void progressControl(long playTime, long seekTime) {
        if (_isLock && mNfwxVideoPlayer.isSeeking()) {
            return;
        }
        gesture_progress_layout.setVisibility(View.VISIBLE);
        gesture_iv_player_volume.setVisibility(View.GONE);
        gesture_iv_player_bright.setVisibility(View.GONE);
        if (seekTime > 0) {
            gesture_progress_layout.setSelected(false);
        } else {
            gesture_progress_layout.setSelected(true);
        }
        geture_tv_progress_percentage.setText(TimeUtil.toTime((int) playTime));
    }

    @Override
    public void progressControlFinish(long playTime) {
        if (_isLock && mNfwxVideoPlayer.isSeeking()) {
            return;
        }
        gesture_progress_layout.setVisibility(View.GONE);
        geture_tv_progress_percentage.setText(TimeUtil.toTime((int) playTime));
        mNfwxVideoPlayer.seekTo(playTime);
    }

    @Override
    public void updateVolume(int currentVolume, int percentage) {
        gesture_volume_layout.setVisibility(View.VISIBLE);
        gesture_iv_player_volume.setVisibility(View.VISIBLE);
        gesture_progress_layout.setVisibility(View.GONE);
        gesture_iv_player_bright.setVisibility(View.GONE);
        if (currentVolume == 0) {
            gesture_iv_player_volume.setSelected(true);
        } else {
            gesture_iv_player_volume.setSelected(false);
        }
        geture_tv_volume_percentage.setText(percentage + "%");
    }

    @Override
    public void updateBrightness(int percentage) {
        gesture_bright_layout.setVisibility(View.VISIBLE);
        gesture_iv_player_volume.setVisibility(View.GONE);
        gesture_progress_layout.setVisibility(View.GONE);
        gesture_iv_player_bright.setVisibility(View.VISIBLE);
        geture_tv_bright_percentage.setText(percentage + "%");
    }

    @Override
    protected void hidePosition() {
        gesture_volume_layout.setVisibility(GONE);
        gesture_bright_layout.setVisibility(GONE);
        gesture_progress_layout.setVisibility(GONE);
    }

    @Override
    protected void hideVolume() {
        gesture_volume_layout.setVisibility(GONE);
        gesture_bright_layout.setVisibility(GONE);
        gesture_progress_layout.setVisibility(GONE);
    }

    @Override
    protected void hideBrightness() {
        gesture_volume_layout.setVisibility(GONE);
        gesture_bright_layout.setVisibility(GONE);
        gesture_progress_layout.setVisibility(GONE);
    }

    @Override
    public boolean isLock() {
        return _isLock;
    }

    @Override
    public boolean isHandPause() {
        return _isHandPause;
    }

    @Override
    public void onPlayStateChanged(int mCurrentState) {
        Log.e("NfwxVideoPlayer", "onPlayStateChanged--" + mCurrentState);
        switch (mCurrentState) {
            case INfwxVideoPlayer.STATE_IDLE:
                if (!_isnetworkError) {
                    showLoading();
                }
                _isHandPause = false;
                break;
            case INfwxVideoPlayer.STATE_PREPARING:
                loadview.removeParentView(view_player);
                if (!isShift()) {
                    cancelUpdateProgressTimer();
                    pcv_home.reset();
                    pcv_home.clearProgramSeek();
                    pcv_home.setSeekEnable(false);
                }
                if (!isClip()) {
                    playView();
                }
                if (!_isnetworkError) {
                    showLoading();
                }
                _isHandPause = false;
                break;
            case INfwxVideoPlayer.STATE_PREPARED:
                if (!_isnetworkError) {
                    showLoading();
                }
                break;
            case INfwxVideoPlayer.STATE_PLAYING:
                if (isClip()) {
                    tvc_controller.seekComplete();
                } else {
                    startUpdateProgressTimer();
                    refreshLiveView();
                    playView();
                }
                if (isHasFragment() || ActivityHelper.getInstance().isBackground()) {
                    NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                }
                hideLoading();
                break;
            case INfwxVideoPlayer.STATE_PAUSED:
                hideLoading();
                stopView();
                cancelUpdateProgressTimer();
                break;
            case INfwxVideoPlayer.STATE_BUFFERING_PLAYING:
                if (!_isnetworkError) {
                    showLoading();
                }
                break;
            case INfwxVideoPlayer.STATE_BUFFERING_PAUSED:
                if (!_isnetworkError) {
                    showLoading();
                }
                break;
            case INfwxVideoPlayer.STATE_ERROR:
                cancelUpdateProgressTimer();
                AccountHelper.getInstance().requestIp(mContext);
                hideLoading();
                if (!isPic()) {
                    loadview.loadError(view_player);
                }
                break;
            case INfwxVideoPlayer.STATE_COMPLETED:
                if (!isLive()) {
                    cancelUpdateProgressTimer();
                    stopView();
                    pcv_home.setProgress(0);
                    hideLoading();
                    mNfwxVideoPlayer.releasePlayer();
                    refreshView(true);
                    playComplete();
                }
                if(isAdvert()){
                    playAdvertComplete();
                }
                break;
            case INfwxVideoPlayer.STATE_SEEKING_START:
                if (!isLive()) {
                    cancelUpdateProgressTimer();
                    refreshView(true);
                    showLoading();
                }
                break;
            case INfwxVideoPlayer.STATE_SEEKING_COMPLETED:
                if (!isLive()) {
                    if (isHandPause()) {
                        hideLoading();
                        startUpdateProgressTimer();
                    } else {
                        startUpdateProgressTimer();
                        playView();
                        hideLoading();
                    }
                }
                break;
        }
    }

    protected boolean isHasFragment() {
        return false;
    }

    @Override
    public void onPlayModeChanged(int mCurrentMode) {

    }

    @Override
    public void reset() {

    }

    @Override
    public void onReceive(Intent intent) {
        player_bar.onReceive(intent);
    }

    @Override
    protected void updateProgress() {
        pcv_home.updatePosiont();
        if (isHasFragment()) {
            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
        }
    }

    @Override
    public boolean onBackPressd() {
        if (!isLive()) {
            backLive();
            return false;
        } else if (isClip()) {
            cancelclip();
            return false;
        } else if (!_isQuit) {
            _isQuit = true;
            ToastUtil.show(mContext, R.string.quit);
            mHandler.sendEmptyMessageDelayed(ACTION_QUIT, 3000);
            return false;
        }
        return true;
    }

    public void stopView() {
        pcv_home.stopView();
    }

    public void playView() {
        pcv_home.playView();
    }

    @Override
    protected void controllVisable() {
        if (isClip()) {
            if (mNfwxVideoPlayer.isPlaying()) {
                tvc_controller.pause();
            } else {
                tvc_controller.play();
            }
            return;
        }
        if (_isReview) {
            _isReview = false;
            AnimationUtil.startSlideToRightAnimation(qrv_review, 300, null);
            qrv_review.setVisibility(View.GONE);
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshView(true);
                }
            }, 300);
            return;
        }
        refreshView(!_isShow);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lock_btn:
                pcv_home.hiddenBubble();
                findView(R.id.lock_btn).setVisibility(View.GONE);
                findView(R.id.unlock_btn).setVisibility(View.VISIBLE);
                hideScreentMenu();
                autoActionHidden();
                break;
            case R.id.unlock_btn:
                pcv_home.hiddenBubble();
                findView(R.id.lock_btn).setVisibility(View.VISIBLE);
                findView(R.id.unlock_btn).setVisibility(View.GONE);
                showScreentMenu();
                autoActionHidden();
                break;
            case R.id.btn_tvprogram:
                openProgram();
                break;
            case R.id.tv_cancle_btn:
            case R.id.tvprogram_cancle_btn:
                refreshView(true);
                break;
            case R.id.tv_vodplayer_back:
            case R.id.vodplayer_back_btn:
                backLive();
                break;
            case R.id.iv_player_btn:
                if (isClip()) {
                    if (mNfwxVideoPlayer.isPlaying()) {
                        _isHandPause = true;
                        tvc_controller.pause();
                    } else {
                        _isHandPause = false;
                        tvc_controller.play();
                    }
                    return;
                }
                if (_isReview) {
                    _isReview = false;
                    AnimationUtil.startSlideToRightAnimation(qrv_review, 300, null);
                    qrv_review.setVisibility(View.GONE);
                    ThreadHelper.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshView(true);
                        }
                    }, 300);
                    return;
                }
                if (mNfwxVideoPlayer.isPlaying()) {
                    NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                    // 手动暂停弹广告
                    _isHandPause = true;
                    AdvertiseController.getInstance().loadPause(mContext, (ImageView) findView(R.id.iv_advertise), getGid());
                    findView(R.id.iv_advertise).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AdvertiseController.getInstance().gotoPauseWeb(mContext, getGid());
                        }
                    });
                } else {
                    _isHandPause = false;
                    findView(R.id.iv_advertise).setVisibility(View.GONE);
                    if (mNfwxVideoPlayer.isCompleted() || _isnetworkError) {
                        reStart();
                    } else {
                        NfwxVideoPlayerManager.instance().resumeVideoPlayer();
                    }
                }
                break;
            case R.id.iv_qpop_quit:
                QuitAppDialogFragment quitAppDialogFragment = QuitAppDialogFragment.newInstance();
                quitAppDialogFragment.setOnQuitListener(new QuitAppDialogFragment.onQuitListener() {
                    @Override
                    public void quitSure() {
                        ActivityHelper.getInstance().exitApp();
                    }
                });
                AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), quitAppDialogFragment);
                break;
            case R.id.download_btn:
                download();
                break;
            case R.id.share_btn:
                share();
                break;
            case R.id.fire_btn://热门视频和频道
                openHotLives();
                break;
            case R.id.search_btn:
                openSearch();
                break;
            case R.id.mine_btn:
                openMine();
                break;
            case R.id.network_sure: // 4g继续播放
                SharePrefUtil.save4gstautus(mContext, true);
                sure4gplay();
                //WifiHelper.stopScan();
                break;
            case R.id.network_free_wifi: // 开启Wi-Fi扫描
                scanWifi();
                break;
            case R.id.iv_audio_play:
                if (mNfwxVideoPlayer.isPlaying()) {
                    iv_audio_play.setSelected(true);
                    NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                    vv_audio_1.cancelAutoData();
                    vv_audio_2.cancelAutoData();
                } else {
                    iv_audio_play.setSelected(false);
                    NfwxVideoPlayerManager.instance().resumeVideoPlayer();
                    vv_audio_1.autoData();
                    vv_audio_2.autoData();
                }
                break;
            case R.id.clip_btn:
                openclip();
                break;
            case R.id.clip_bottom_cancle: //取消剪切视频
                cancelclip();
                break;
            case R.id.clip_bottom_sure: // 确定剪切视频的分享
                sureclip();
                break;
            case R.id.review_btn: // 回看
                openReview();
                break;
            case R.id.svga_iv:
                if (isLock()) {
                    return;
                }
                AdvertiseController.getInstance().gotoJiaoBiaoWeb(mContext, getGid());
                break;
            case R.id.company_btn:
                openCompany();
                break;
            case R.id.player_size_change:
                if (v.isSelected()) {
                    v.setSelected(false);
                    mNfwxVideoPlayer.enterSmalledScreen();
                } else {
                    v.setSelected(true);
                    mNfwxVideoPlayer.enterBigedScreen();
                }
                break;
        }
    }

    @Override
    public void onNetworkChange(int networkType) {
        if (networkType == NetworkUtil.NO_NETWORK) {
            _isnetworkError = true;
            if (isClip() || isDownedPlay()) {
                return;
            }
            if (mNfwxVideoPlayer != null) {
                pcv_home.clearProgramSeek();
                pcv_home.reset();
                hideLoading();
                NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                mNfwxVideoPlayer.clearScreen();
            }
            findView(R.id.iv_advertise).setVisibility(View.GONE);

            loadview.netError(view_player);
            DownloadM3u8Controller.getInstance().pauseAll(mContext);
            SharePrefUtil.save4gstautus(mContext, false);
        } else if (networkType == NetworkUtil.G_NETWORK) {
            _isnetworkError = true;
            if (isClip() || isDownedPlay()) {
                return;
            }
            if (mNfwxVideoPlayer != null) {
                pcv_home.clearProgramSeek();
                pcv_home.reset();
                hideLoading();
                NfwxVideoPlayerManager.instance().suspendVideoPlayer();
                mNfwxVideoPlayer.clearScreen();
            }
            AccountHelper.getInstance().requestIp(mContext);
            findView(R.id.iv_advertise).setVisibility(View.GONE);
            SharePrefUtil.save4gstautus(mContext, false);
            loadview.net4gError(view_player);
            if (!SharePrefUtil.getDownloadChoose(mContext)) {
                DownloadM3u8Controller.getInstance().pauseAll(mContext);
            }
        } else if (networkType == NetworkUtil.WIFI_NETWORK ||
                networkType == NetworkUtil.LINE_NETWORK) {
            AccountHelper.getInstance().requestIp(mContext);
            //WifiHelper.getInstance().checkWifiResume(mContext);
            loadview.removeParentView(view_player);
            // 手动隐藏广告
            _isnetworkError = false;
            findView(R.id.iv_advertise).setVisibility(View.GONE);
            reStart();
        }
    }

    /**
     * 自动隐藏底部栏
     */
    protected void autoActionHidden() {
        mHandler.removeMessages(ACTION_HIDDEN);
        mHandler.sendEmptyMessageDelayed(ACTION_HIDDEN, HIDDENTIME);
    }

    /**
     * 取消隐藏底部栏
     */
    protected void cancelActionHidden() {
        mHandler.removeMessages(ACTION_HIDDEN);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case ACTION_LAUNCHER:
                //iv_launcher.setVisibility(View.GONE);
                // 显示引导图
                break;
            case ACTION_SHOW:
                //refreshLiveView(_isLive);
                refreshView(true);
                break;
            case ACTION_HIDDEN:
                refreshView(false);
                break;
            case ACTION_QUIT:
                _isQuit = false;
                break;
            case ACTION_LOAD: // 5分钟刷新一次数据
                break;
            case ACTION_TITLE:
                player_bar.update();
                mHandler.sendEmptyMessageDelayed(ACTION_TITLE, TITLE_TIME_UPDATE);
                break;
            case ACTION_JIAOBIAO:
                if (!isClip()) {
                    svga_iv.setClickable(false);
                    int stats = AdvertiseController.getInstance().loadJiaoBiao(mContext, svga_iv, getGid());
                    if (stats == AdvertiseController.IMG_TYPE_SVGA) {
                        mHandler.removeMessages(ACTION_JIAOBIAO_HIDDEN);
                    } else if (stats == AdvertiseController.IMG_TYPE_PNG) {
                        mHandler.removeMessages(ACTION_JIAOBIAO);
                        mHandler.removeMessages(ACTION_JIAOBIAO_HIDDEN);
                        mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO_HIDDEN, AdvertiseController.getInstance().getDurTime(mContext, TYPE_JIAOBIAO));
                    } else if (stats == AdvertiseController.IMG_TYPE_NO) {
                        mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO, JIAOBIAOTIME);
                    }
                }
                break;
            case ACTION_JIAOBIAO_HIDDEN:
                svga_iv.setImageDrawable(null);
                svga_iv.setClickable(false);
                mHandler.removeMessages(ACTION_JIAOBIAO);
                mHandler.sendEmptyMessageDelayed(ACTION_JIAOBIAO, AdvertiseController.getInstance().getInterval(mContext, TYPE_JIAOBIAO, getGid()));
                break;
        }
        return false;
    }

    /**
     * 播放变化
     */
    protected void refreshLiveView() {
        changeLiveView();
        loadview.removeParentView(view_player);
        // 手动隐藏广告
        if (!isShift()) {
            pcv_home.refreshProgramSeek();
            pcv_home.setSeekEnable(true);
            pcv_home.refreshView();
        }
        if (isAudio()) {
            ll_audio.setVisibility(View.VISIBLE);
            pcv_home.setVisibility(View.INVISIBLE);
            iv_audio_play.setSelected(false);
            vv_audio_1.autoData();
            vv_audio_2.autoData();
            player_right.setVisibility(View.GONE);
        } else {
            vv_audio_1.cancelAutoData();
            vv_audio_2.cancelAutoData();
//            if (_isClip) {
//                player_right.setVisibility(View.GONE);
//            } else {
//                player_right.setVisibility(View.VISIBLE);
//            }
            ll_audio.setVisibility(View.GONE);
        }
    }

    /**
     * 更新剪切布局
     *
     * @param status
     */
    protected void refreshClip(boolean status) {
        if (status) {
            _isClip = true;
            AnimationUtil.startFromBottomAnimation(tvc_controller, 300, null);
            tvc_controller.setVisibility(View.VISIBLE);
            AnimationUtil.startToBottomAnimation(player_bottom, 300, null);
            AnimationUtil.startTopAnimation(ll_home_top, 300, null, 0.0f, -1.0f);
            AnimationUtil.startSlideToRightAnimation(player_right, 300, null);
            AnimationUtil.startSlideToLeftAnimation(rl_player_left, 300, null);
            player_bottom.setVisibility(View.GONE);
            player_right.setVisibility(View.GONE);
            ll_home_top.setVisibility(View.GONE);
            rl_player_left.setVisibility(View.GONE);
            cancelActionHidden();
        } else {
            _isClip = false;
            AnimationUtil.startToBottomAnimation(tvc_controller, 300, null);
            tvc_controller.setVisibility(View.GONE);
            AnimationUtil.startFromBottomAnimation(player_bottom, 300, null);
            AnimationUtil.startTopAnimation(ll_home_top, 300, null, -1.0f, 0.0f);
            AnimationUtil.startSlideFromRightAnimation(player_right, 300, null);
            AnimationUtil.startSlideFromLeftAnimation(rl_player_left, 300, null);
            player_bottom.setVisibility(View.VISIBLE);
            player_right.setVisibility(View.VISIBLE);
            ll_home_top.setVisibility(View.VISIBLE);
            rl_player_left.setVisibility(View.VISIBLE);
            autoActionHidden();
        }
    }

    /**
     * 直播，点播的ui变化
     */
    protected void changeLiveView() {
        if (isLive()) {
            ll_bottom.setVisibility(View.VISIBLE);
            tv_qpop_quit.setVisibility(View.GONE);
            iv_qpop_quit.setVisibility(View.VISIBLE);
            tv_vodplayer_back.setVisibility(View.GONE);
            vodplayer_back_btn.setVisibility(View.GONE);
        } else {
            ll_bottom.setVisibility(View.GONE);
            tv_qpop_quit.setVisibility(View.GONE);
            iv_qpop_quit.setVisibility(View.GONE);
            tv_vodplayer_back.setVisibility(View.VISIBLE);
            vodplayer_back_btn.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 锁屏
     */
    private void hideScreentMenu() {
        _isLock = true;
        _isShow = false;
        AnimationUtil.startToBottomAnimation(player_bottom, durationMillis, null);
        AnimationUtil.startTopAnimation(ll_home_top, durationMillis, null, 0.0f, -1.0f);
        AnimationUtil.startSlideToRightAnimation(player_right, durationMillis, null);
        //_player.setEnabled(false);
        //playerViewController.setEnable(false);
        player_bottom.setVisibility(View.GONE);
        player_right.setVisibility(View.GONE);
        ll_home_top.setVisibility(View.GONE);
        cancelActionHidden();
    }

    /**
     * 解锁屏幕
     */
    private void showScreentMenu() {
        _isLock = false;
        _isShow = true;
        AnimationUtil.startFromBottomAnimation(player_bottom, durationMillis, null);
        AnimationUtil.startTopAnimation(ll_home_top, durationMillis, null, -1.0f, 0.0f);
        AnimationUtil.startSlideFromRightAnimation(player_right, durationMillis, null);
        //_player.setEnabled(true);
        //playerViewController.setEnable(true);
        player_bottom.setVisibility(View.VISIBLE);
        player_right.setVisibility(View.VISIBLE);
        ll_home_top.setVisibility(View.VISIBLE);
        autoActionHidden();
    }

    /**
     * 是否显示
     *
     * @param isShow
     */
    protected void refreshView(boolean isShow) {
        if (_isLock) {
            if (rl_player_left.getVisibility() == View.GONE) {
                AnimationUtil.startSlideFromLeftAnimation(rl_player_left, durationMillis, null);
                rl_player_left.setVisibility(View.VISIBLE);
            } else if (rl_player_left.getVisibility() == View.VISIBLE) {
                AnimationUtil.startSlideToLeftAnimation(rl_player_left, durationMillis, null);
                rl_player_left.setVisibility(View.GONE);
            }
            return;
        }
        if (_isShow == isShow) {
            return;
        }
        _isShow = isShow;
        if (_isShow) {
            AnimationUtil.startFromBottomAnimation(player_bottom, durationMillis, null);
            AnimationUtil.startTopAnimation(ll_home_top, durationMillis, null, -1.0f, 0.0f);
            AnimationUtil.startSlideFromRightAnimation(player_right, durationMillis, null);
            player_bottom.setVisibility(View.VISIBLE);
            ll_home_top.setVisibility(View.VISIBLE);
            player_right.setVisibility(View.VISIBLE);
            AnimationUtil.startSlideFromLeftAnimation(rl_player_left, durationMillis, null);
            rl_player_left.setVisibility(View.VISIBLE);
            autoActionHidden();
            pcv_home.refreshProgramSeek(); // 每次打开重新刷新一次位置
        } else {
            AnimationUtil.startToBottomAnimation(player_bottom, durationMillis, null);
            AnimationUtil.startTopAnimation(ll_home_top, durationMillis, null, 0.0f, -1.0f);
            AnimationUtil.startSlideToRightAnimation(player_right, durationMillis, null);
            player_bottom.setVisibility(View.GONE);
            ll_home_top.setVisibility(View.GONE);
            player_right.setVisibility(View.GONE);
            AnimationUtil.startSlideToLeftAnimation(rl_player_left, durationMillis, null);
            rl_player_left.setVisibility(View.GONE);
            cancelActionHidden();
            tv_qpop_quit.setVisibility(View.GONE);
            pcv_home.hiddenBubble();
        }
    }

    /**
     * 设置时移状态
     */
    public void setShift(boolean isShift) {

    }

    /**
     * 是否是图片
     *
     * @return
     */
    protected boolean isPic() {
        return false;
    }

    protected void scanWifi() {

    }

    /**
     * 弹出网络提示
     */
    public void showNet() {
        BaseDialogFragment dialogFragment;
        AppCompatActivity activity = AppUtil.getAppCompActivity(mContext);
        View view = findView(R.id.content);
        List<Fragment> fragments = activity.getSupportFragmentManager().getFragments();
        if (!fragments.isEmpty()) {
            final Fragment fragment = fragments.get(fragments.size() - 1);
            if (fragment instanceof BaseDialogFragment) {
                if (fragment.isVisible()) {
                    dialogFragment = (BaseDialogFragment) fragment;
                    view = dialogFragment.getView();
                }
            }
        }
        // 预约节目结束跳转至我的预约界面反则查看对应的直播
        TSnackbarUtil.showNetTSnackbar(view, activity.getString(R.string.network_toast));
    }

    @Override
    public void callbackByfragment(String action, Bundle bundle) {
        switch (action) {
            case TVProgramsViewController.ACTION_PROGRAM_CLICK:
            case TVHotViewController.ACTION_HOT_CLICK:
                if (bundle != null) {
                    int viewId = bundle.getInt("id", -1);
                    if (viewId == R.id.tvprogram_cancle_btn
                            || viewId == R.id.tv_cancle_btn) {
                        refreshView(true);
                    }
                }
                break;
        }
    }
}
